<?php

function spotify_artist_id($name){
	$response = spotify_xml('search/1/artist?q=artist:'.urlencode($name));
	$xml = new SimpleXMLElement($response);
	$href = $xml->artist[0]['href'];
	return substr($href,strrpos($href, ':')+1);
}


function _spotify_albums_by_artist($spotify_id,$artist_id,$expiry = null){

	if($expiry && $expiry < time()){
		
		if($result = mysql_query("SELECT s.name,s.spotify_album "
		."FROM spotify_cache s,artist a "
		."WHERE s.artist_id = a.id AND s.territories LIKE '%GB%'AND a.id=".$artist_id)){
			while($row = mysql_fetch_assoc($result)){
				$albums[] = array(
	   		'name' => $row['name'],
	   		'id' => $row['spotify_album'],
				);
			}
		}
		
	} else {
		$response = spotify_xml('lookup/1/?uri=spotify:artist:'.$spotify_id.'&extras=album');
		$xml = new SimpleXMLElement($response);
		$values = array();
		//make big insert of spotify values
		foreach ($xml->albums->album as $album) {
			$album_id = substr($album['href'],strrpos($album['href'], ':')+1);
			$values[] = "(".$artist_id
			.",'".mysql_escape_string($album_id)."'"
			.",'".mysql_escape_string($album->name)."'"
			.",'".mysql_escape_string($album->availability->territories)."')";
			if(strpos($album->availability->territories,'GB')){
				$albums[] = array(
			   		'name' => $album->name,
			   		'id' => $album_id,
				);
			}
		}

		db_query("UPDATE artist SET spotify_artist= '%s',spotify_expiry='%s' WHERE id=%d",
		array($spotify_id,
		date ("Y-m-d H:i:s",mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"))),
		$artist_id));
		if(count($values) > 0){
			//delete existing and insert new
			//		mysql_query("START TRANSACTION");
			db_query("DELETE FROM spotify_cache WHERE artist_id = %d",$artist_id);
			$sql = "INSERT INTO spotify_cache VALUES ".implode(",",$values);
//			print $sql;
			mysql_query($sql);
			//		mysql_query("COMMIT");
		}
	}
	return $albums;
}


function spotify_albums_by_artist($artist,$artist_id, $spotify_id = null,$expiry = null){
	if($spotify_id){
		return _spotify_albums_by_artist($spotify_id,$artist_id,$expiry);
	} else {
		$id = spotify_artist_id($artist);
		return _spotify_albums_by_artist($id,$artist_id,$expiry);
	}
}

function spotify_xml($request){



	// Request Yahoo! REST Web Service using
	// HTTP POST with curl. PHP4/PHP5
	// Allows retrieval of HTTP status code for error reporting
	// Author: Jason Levitt
	// February 1, 2006

	error_reporting(E_ALL);

	// The POST URL and parameters
	//	$request =  'http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction';
	//	$appid = 'YahooDemo';
	//	$context = 'Italian sculptors and painters of the renaissance favored the Virgin Mary for inspiration';
	//	$query = 'madonna';

	//	$postargs = 'foo='.urlencode($bar);

	// Get the curl session object
	$session = curl_init('http://ws.spotify.com/'.$request);

	// Set the POST options.
	//	curl_setopt ($session, CURLOPT_POST, true);
	//	curl_setopt ($session, CURLOPT_POSTFIELDS, $postargs);
	curl_setopt($session, CURLOPT_HEADER, true);
	curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

	// Do the POST and then close the session
	$response = curl_exec($session);
	curl_close($session);

	// Get HTTP Status code from the response
	$status_code = array();
	preg_match('/\d\d\d/', $response, $status_code);

	// Check for errors
	switch( $status_code[0] ) {
		case 200:
			// Success
			break;
		case 503:
			die('Your call to the Spotify API failed and returned an HTTP status of 503. That means: Service unavailable. An internal problem prevented us from returning data to you.');
			break;
		case 403:
			die('Your call to the Spotify API failed and returned an HTTP status of 403. That means: Forbidden. You do not have permission to access this resource, or are over your rate limit.');
			break;
		case 400:
			// You may want to fall through here and read the specific XML error
			die('Your call to the Spotify API failed and returned an HTTP status of 400. That means:  Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.');
			break;
		default:
			die('Your call to the Spotify API returned an unexpected HTTP status of:' . $status_code[0]);
	}

	// Get the XML from the response, bypassing the header
	if (!($xml = strstr($response, '<?xml'))) {
		$xml = false;
	}



	// Output the XML
	return $xml;

}